﻿/********************************************************************************
    Copyright (C) Binod Nepal, Planet Earth Solutions Pvt. Ltd., Kathmandu.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Drawing;
using MixNP.BusinessLayer.Helpers;

namespace MixNP.Web.Handlers
{
    /// <summary>
    /// Summary description for GetProfilePicture
    /// </summary>
    public class GetProfilePicture : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string file = context.Request.QueryString["Path"].ToString();

            if (string.IsNullOrWhiteSpace(file))
            {
                MixNP.BusinessLayer.Helpers.PageHelper.ContentNotFound(context);
            }

            ProcessImage(context);
        }

        private static void ProcessImage(HttpContext context)
        {
            string path = string.Empty;
            int width = 0;
            int height = 0;

            string emailAddress = MixNP.BusinessLayer.Users.GetEmailAddressFromSalt(context.Request.QueryString["Path"]);
            bool IsProfilePictureProtected = MixNP.BusinessLayer.Profiles.IsProfilePictureProtected(emailAddress);
            string optionalText = string.Empty;
            string userIdentityName = HttpContext.Current.User.Identity.Name;
            string sessionUserId = Pes.Utility.Conversion.TryCastString(context.Session["UserId"]);
            
            if (!string.IsNullOrWhiteSpace(context.Request.QueryString["Path"]))
            {
                path = "~/Classifieds/ProfilePictures/" + emailAddress + MixNP.BusinessLayer.Users.GetProfilePictureExtension(emailAddress);
            }

            if (IsProfilePictureProtected)
            {
                optionalText = "You profile picture is protected.";

                if (sessionUserId != emailAddress)
                {
                    optionalText = "";
                    path = "~/Classifieds/Images/404/5.png";
                }
            }


            if (!string.IsNullOrWhiteSpace(context.Request.QueryString["W"]))
            {
                width = Convert.ToInt32(context.Request.QueryString["W"], CultureInfo.InvariantCulture);
            }

            if (!string.IsNullOrWhiteSpace(context.Request.QueryString["H"]))
            {
                height = Convert.ToInt32(context.Request.QueryString["H"], CultureInfo.InvariantCulture);
            }

            context.Response.Clear();

            if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                MixNP.BusinessLayer.Helpers.PageHelper.ContentNotFound(context);
            }
            else
            {
                System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
                using (Bitmap originalImage = new Bitmap(context.Server.MapPath(path)))
                {
                    byte[] buffer = ImageHelper.GetResizedImage(MixNP.BusinessLayer.Helpers.WaterMark.WarterMark(originalImage, context, optionalText), width, height);

                    context.Response.ContentType = ImageHelper.GetContentType(file.Extension);
                    context.Response.Cache.SetCacheability(HttpCacheability.Public);
                    context.Response.Cache.SetExpires(DateTime.Now.AddMonths(1));
                    context.Response.Cache.SetMaxAge(new TimeSpan(30, 0, 0, 0, 0));
                    context.Response.AddHeader("Last-Modified", DateTime.Now.ToShortDateString());

                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    context.Response.End();
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}